<template>
  <div class="applicationRecord-list">
    <div class="breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item to="Home" :replace="true">首页</el-breadcrumb-item>
        <el-breadcrumb-item>应聘申请列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-form :inline="true" :model="applicationRecordQueryForm" ref="applicationRecordQueryFormRef" :rules="rules">
      <el-form-item label="企业名称" prop="enterpriseName">
        <el-input v-model="applicationRecordQueryForm.enterpriseName" placeholder="请选择企业名称" readonly="readonly">
          <template #suffix>
            <el-icon @click="findEnterprise"><Search/></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="招聘岗位名称" prop="jobDescriptionName">
        <el-input v-model="applicationRecordQueryForm.jobDescriptionName" placeholder="请选择招聘岗位名称" readonly="readonly">
          <template #suffix>
            <el-icon @click="findJobDescription"><Search/></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="应聘者姓名" prop="candidateName" v-if="findCandidateFormItem">
        <el-input v-model="applicationRecordQueryForm.candidateName" placeholder="请选择应聘者姓名" readonly="readonly">
          <template #suffix>
            <el-icon @click="findCandidate"><Search/></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="applicationRecordQueryForm.status" placeholder="请选择状态" class="select-custom">
          <el-option label="申请" :value="10"></el-option>
          <el-option label="面试邀约" :value="20"></el-option>
          <el-option label="录用" :value="30"></el-option>
          <el-option label="拒绝" :value="90"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button @click="onReset">重置</el-button>
        <el-button type="primary" @click="onAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table
      :data="state.tableData"
      border
      v-loading="state.loading"
      size="small"
      header-cell-class-name="table-header-cell-font"
      cell-class-name="table-cell-font">
      <el-table-column prop="enterpriseName" label="企业名称"></el-table-column>
      <el-table-column prop="jobDescriptionName" label="招聘岗位名称"></el-table-column>
      <el-table-column prop="candidateName" label="应聘者姓名"></el-table-column>
      <el-table-column prop="status" label="状态">
        <template v-slot="{ row }">
          <div v-if="row.status === 10">申请</div>
          <div v-if="row.status === 20">面试邀约</div>
          <div v-if="row.status === 30">录用</div>
          <div v-if="row.status === 90">拒绝</div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="350">
        <template v-slot="{ row }">
          <el-button @click.prevent="editRow(row.id)" type="primary">编辑</el-button>
          <el-button @click.prevent="delRow(row.id)" type="danger" plain>删除</el-button>
          <el-button @click.prevent="detailRow(row.id)" type="primary" plain>详情</el-button>
          <el-button @click.native.prevent="candidateRow(row.candidateId)" type="primary" plain>应聘者详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="table-pagination">
      <el-pagination
        @current-change="changePage"
        :current-page="state.currentPage"
        :page-sizes="state.pageSizes"
        :page-size="state.pageSize"
        background
        layout="total, prev, pager, next, jumper"
        :total="state.total">
      </el-pagination>
    </div>
    <el-dialog v-model="enterpriseSelectorVisible" v-if="enterpriseSelectorVisible" title="企业信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <enterprise-selector @enterprise-selected-event="handleEnterpriseSelectedEvent">
      </enterprise-selector>
    </el-dialog>
    <el-dialog v-model="jobDescriptionSelectorVisible" v-if="jobDescriptionSelectorVisible" title="招聘岗位选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <job-description-selector @job-description-selected-event="handleJobDescriptionSelectedEvent">
      </job-description-selector>
    </el-dialog>
    <el-dialog v-model="candidateSelectorVisible" v-if="candidateSelectorVisible" title="应聘者基本信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <candidate-selector @candidate-selected-event="handleCandidateSelectedEvent">
      </candidate-selector>
    </el-dialog>
    <el-dialog v-model="applicationRecordAddVisible" v-if="applicationRecordAddVisible" :title="applicationRecordAddTitle" :top="dialogTop" :width="dialogWidth">
      <application-record-add :id="selectedApplicationRecordId" @close-application-record-add-event="handleCloseApplicationRecordAddEvent" @reset-application-record-add-event="handleResetApplicationRecordAddEvent">
      </application-record-add>
    </el-dialog>
    <el-dialog v-model="applicationRecordViewVisible" v-if="applicationRecordViewVisible" title="应聘申请详情" :top="dialogTop" :width="dialogWidth">
      <application-record-view :id="selectedApplicationRecordId" @close-application-record-view-event="handleCloseApplicationRecordViewEvent">
      </application-record-view>
    </el-dialog>
    <el-dialog v-model="candidateViewAllVisible" v-if="candidateViewAllVisible" title="应聘者详情" :top="dialogTop" :width="dialogWidth">
      <candidate-view-all :id="selectedCandidateId" @close-candidate-view-all-event="handleCandidateViewAllEvent">
      </candidate-view-all>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref, inject, toRefs} from 'vue';
import applicationRecordApi from '@/api/applicationRecordApi'
import type {ApplicationRecordQueryForm} from "@/types/req/applicationRecordQueryForm";
import type {ApplicationRecord} from "@/types/resp/applicationRecord";
import {ElMessage, ElMessageBox, type FormInstance} from "element-plus";
import type {Result} from "@/types/result";
import type {Page} from "@/types/page";
import { Search } from '@element-plus/icons-vue';
import EnterpriseSelector from "@/views/enterprise/EnterpriseSelector.vue";
import JobDescriptionSelector from "@/views/jobDescription/JobDescriptionSelector.vue";
import CandidateSelector from "@/views/candidate/CandidateSelector.vue";
import ApplicationRecordAdd from "@/views/applicationRecord/ApplicationRecordAdd.vue"
import ApplicationRecordView from "@/views/applicationRecord/ApplicationRecordView.vue"
import CandidateViewAll from "@/views/candidate/CandidateViewAll.vue";

const applicationRecordQueryFormRef = ref<FormInstance | null>(null);
const applicationRecordQueryForm = reactive<ApplicationRecordQueryForm>({
  enterpriseId: 0,
  enterpriseName: '',
  jobDescriptionId: 0,
  jobDescriptionName: '',
  candidateId: 0,
  candidateName: '',
  status: undefined,
})

const state = reactive({
  loading: false,
  tableData: [] as ApplicationRecord[], // 数据列表
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10, // 分页大小
  pageSizes: [10, 20, 50]
})
const selectedApplicationRecordId = ref<number>(0)
const enterpriseSelectorVisible = ref<boolean>(false)
const jobDescriptionSelectorVisible = ref<boolean>(false)
const candidateSelectorVisible = ref<boolean>(false)
const applicationRecordAddVisible = ref<boolean>(false)
const applicationRecordViewVisible = ref<boolean>(false)
const findCandidateFormItem = ref<boolean>(false)
const candidateViewAllVisible = ref<boolean>(false)
const selectedCandidateId = ref<number>(0)
const applicationRecordAddTitle = ref<string>('')
const dialogTop = ref<string>('')
const dialogWidth = ref<string>('')

const rules = reactive({
});

const initByType = () => {
  const type = sessionStorage.getItem('type')
  if (type && Number(type) === 3) {
    applicationRecordQueryForm.candidateId = 2
    findCandidateFormItem.value = false
  }
}

onMounted(() => {
  initByType()
  onSearch()
  const globalState = inject('globalState', {} as { dialogWidth?: string, dialogTop?: string })
  if (!globalState) {
    throw new Error('globalState is not provided');
  }
  const globalStateRefs = toRefs(globalState)
  if (globalStateRefs.dialogWidth) {
    dialogWidth.value = globalStateRefs.dialogWidth.value || ''
  }
  if (globalStateRefs.dialogTop) {
    dialogTop.value = globalStateRefs.dialogTop.value || ''
  }
})

const getPageData = async () => {
  try {
    state.loading = true
    const resp: Result<Page<ApplicationRecord>> = await applicationRecordApi.find(applicationRecordQueryForm)
    if (resp && resp.code === 1) {
      if (resp.data) {
      const page: Page<ApplicationRecord> = resp.data
        if (page && page.list.length > 0) {
          state.tableData = page.list
          state.total = page.total
        }
      }
    }
  } catch (e) {
    console.log('获取数据异常', e)
  } finally {
    state.loading = false
  }
}
const onSearch = () => {
  getPageData()
}

const changePage = (val: number) => {
  state.currentPage = val
  getPageData()
}

const onReset = () => {
  if (applicationRecordQueryFormRef.value) {
    applicationRecordQueryFormRef.value.resetFields()
  }
  state.currentPage = 1
  getPageData()
}

const onAdd = () => {
  selectedApplicationRecordId.value = 0
  applicationRecordAddVisible.value = true
  applicationRecordAddTitle.value = '应聘申请新增'
}
const editRow = (id: number) => {
  selectedApplicationRecordId.value = id
  applicationRecordAddVisible.value = true
  applicationRecordAddTitle.value = '应聘申请编辑'
}
const delRow = (id: number) => {
  if (!id) {
    return
  }
  ElMessageBox.confirm(
    '确定要删除吗?',
    '删除提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    applicationRecordApi.del(id)
      .then((resp) => {
        if (resp && resp.code === 1) {
          ElMessage.success('删除成功!')
          onSearch()
        } else {
          ElMessage.error('操作失败:' + (resp.msg ? resp.msg : '原因未知'))
        }
      })
      .catch(error => {
        console.error('操作失败:', error)
      })
  }).catch(() => {})
}
const detailRow = (id:number) => {
  selectedApplicationRecordId.value = id
  applicationRecordViewVisible.value = true
}

const findEnterprise = () => {
  enterpriseSelectorVisible.value = true
}

const handleEnterpriseSelectedEvent = (selectedEnterprise: any) => {
  enterpriseSelectorVisible.value = false
  if (selectedEnterprise && 'enterpriseId' in selectedEnterprise && applicationRecordQueryForm.enterpriseId !== selectedEnterprise['enterpriseId']) {
    applicationRecordQueryForm.enterpriseId = selectedEnterprise['enterpriseId']
    applicationRecordQueryForm.enterpriseName = selectedEnterprise['enterpriseName']
  }
}
const findJobDescription = () => {
  jobDescriptionSelectorVisible.value = true
}

const handleJobDescriptionSelectedEvent = (selectedJobDescription: any) => {
  jobDescriptionSelectorVisible.value = false
  if (selectedJobDescription && 'jobDescriptionId' in selectedJobDescription && applicationRecordQueryForm.jobDescriptionId !== selectedJobDescription['jobDescriptionId']) {
    applicationRecordQueryForm.jobDescriptionId = selectedJobDescription['jobDescriptionId']
    applicationRecordQueryForm.jobDescriptionName = selectedJobDescription['jobDescriptionName']
  }
}
const findCandidate = () => {
  candidateSelectorVisible.value = true
}

const handleCandidateSelectedEvent = (selectedCandidate: any) => {
  candidateSelectorVisible.value = false
  if (selectedCandidate && 'candidateId' in selectedCandidate && applicationRecordQueryForm.candidateId !== selectedCandidate['candidateId']) {
    applicationRecordQueryForm.candidateId = selectedCandidate['candidateId']
    applicationRecordQueryForm.candidateName = selectedCandidate['candidateName']
  }
}

const handleCloseApplicationRecordViewEvent = () => {
  applicationRecordViewVisible.value = false
}

const handleResetApplicationRecordAddEvent = () => {
  applicationRecordAddTitle.value = '应聘申请新增'
}

const handleCloseApplicationRecordAddEvent = (params: { search?: boolean } | undefined) => {
  if (params && params.search) {
    onSearch()
  }
  applicationRecordAddVisible.value = false
}

const candidateRow = (candidateId: number) => {
  selectedCandidateId.value = candidateId
  candidateViewAllVisible.value = true
}

const handleCandidateViewAllEvent = () => {
  candidateViewAllVisible.value = false
}
</script>

<style lang="scss">
</style>